﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace ZhCun.WebUtils
{
    /// <summary>
    /// json 帮助类
    /// </summary>
    public static class JsonHelper
    {
        static JsonHelper()
        {
            Options = new JsonOptions();
            SetJsonOption(Options);

            //Options.JsonSerializerOptions.PropertyNamingPolicy = null;
            //Options.JsonSerializerOptions.Converters.Add(DateTimeConverter.Instance);
            //Options.JsonSerializerOptions.Converters.Add(DateTimeNullableConverter.Instance);
        }

        public static void SetJsonOption(JsonOptions options)
        {
            if (options == null) options = new JsonOptions();
            options.JsonSerializerOptions.PropertyNamingPolicy = null;
            options.JsonSerializerOptions.Converters.Add(DateTimeConverter.Instance);
            options.JsonSerializerOptions.Converters.Add(DateTimeNullableConverter.Instance);
        }

        public static JsonOptions Options { get; private set; }

        public static T Deserialize<T>(string json)
        {
            return JsonSerializer.Deserialize<T>(json, Options.JsonSerializerOptions);
        }

        public static string Serialize<T>(T tVal)
        {
            return JsonSerializer.Serialize(tVal, Options.JsonSerializerOptions);
        }
    }

    class DateTimeConverter : JsonConverter<DateTime>
    {
        static DateTimeConverter()
        {
            Instance = new DateTimeConverter();
        }

        public static DateTimeConverter Instance { get; }

        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            return DateTime.Parse(reader.GetString());
        }

        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss"));
        }
    }

    class DateTimeNullableConverter : JsonConverter<DateTime?>
    {

        static DateTimeNullableConverter()
        {
            Instance = new DateTimeNullableConverter();
        }

        public static DateTimeNullableConverter Instance { get; }


        public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            return string.IsNullOrEmpty(reader.GetString()) ? default(DateTime?) : DateTime.Parse(reader.GetString());
        }

        public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value?.ToString("yyyy-MM-dd HH:mm:ss"));
        }
    }
}